from .settings import *
import pymysql


class Connect:

    def __init__(self):
        '''初始化函数连接数据库和创建游标'''
        self.conn = pymysql.connect(
            host=HOST,
            port=PORT,
            user=USER,
            password=PASSWORD,
            db=DB,
            charset=CHARSET,
        )
        self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)

        self.last_id_sql = 'SELECT LAST_INSERT_ID()'

    def __enter__(self):
        '''上下文管理的enter方法'''
        return self

    def __exit__(self, *exc_info):
        '''上下文管理的exit方法'''
        if exc_info:
            self.conn.rollback()
        self.closer()

    def closer(self):
        '''关闭数据库'''
        self.cursor.close()
        self.conn.close()

    def insert(self, sql, args=None):
        if args == None:
            self.cursor.execute(sql)
        else:
            self.cursor.execute(sql, args)
        self.conn.commit()

        ID = self.select_one(self.last_id_sql)['LAST_INSERT_ID()']

        self.conn.commit()

        return ID

    def select_all(self, sql, args=None):
        '''查询表中所有的信息'''
        if args == None:
            self.cursor.execute(sql)
        else:
            self.cursor.execute(sql, args)
        result_info = self.cursor.fetchall()
        return result_info

    def select_one(self, sql, args=None):
        '''查询表中单个对应的信息'''
        if args == None:
            self.cursor.execute(sql)
        else:
            self.cursor.execute(sql, args)
        result_info = self.cursor.fetchone()
        return result_info

    def delete(self, sql, args=None):
        if args == None:
            self.cursor.execute(sql)
        else:
            self.cursor.execute(sql, args)
        result_info = self.cursor.fetchall()
        return result_info

    def update(self, sql, args=None):
        if args == None:
            self.cursor.execute(sql)
        else:
            self.cursor.execute(sql, args)
            self.conn.commit()
        return '修改成功'
